package cate.game.pay;

import cate.game.common.scanner.GameScanner;
import cate.game.common.scanner.IScanner;

import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

public class PayHandlerScanner implements IScanner {
    public static final Map<Integer, Class<? extends PayCallback>> HANDLERS = new HashMap<>();

    public PayHandlerScanner() {
        GameScanner.registScanner(this);
    }

    @Override
    public boolean match(Class<?> clazz) {
        return PayCallback.class.isAssignableFrom(clazz) && !clazz.isInterface() && !Modifier.isAbstract(clazz.getModifiers());
    }

    @Override
    @SuppressWarnings("unchecked")
    public void handle(Class<?> clazz) {
        PayHandler payHandler = clazz.getAnnotation(PayHandler.class);
        if (payHandler != null) {
            int[] funcIds = payHandler.funcIds();
            for (int funcId : funcIds) {
                try {
                    HANDLERS.put(funcId, (Class<? extends PayCallback>) clazz);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void afterScan() {

    }

    public PayCallback getPayHandler(int funcId) {
        Class<? extends PayCallback> clazz = HANDLERS.get(funcId);
        if (clazz != null) {
            PayCallback payCallback = null;
            try {
                payCallback = clazz.getConstructor().newInstance();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return payCallback;
        }
        return null;
    }
}
